import type { NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

/**
 * 认证路由守卫
 */
export const authGuard = (
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) => {
  const authStore = useAuthStore()
  
  // 需要认证的路由
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  
  // 只允许游客访问的路由（如登录、注册页）
  const guestOnly = to.matched.some(record => record.meta.guestOnly)
  
  if (requiresAuth && !authStore.isAuthenticated) {
    // 需要认证但未登录，跳转到登录页
    next({
      name: 'login',
      query: { redirect: to.fullPath }
    })
  } else if (guestOnly && authStore.isAuthenticated) {
    // 已登录用户访问游客页面，跳转到首页
    next({ name: 'home' })
  } else {
    // 允许访问
    next()
  }
}

/**
 * 管理员路由守卫
 */
export const adminGuard = (
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) => {
  const authStore = useAuthStore()
  
  // 检查是否需要管理员权限
  const requiresAdmin = to.matched.some(record => record.meta.requiresAdmin)
  
  if (requiresAdmin) {
    if (!authStore.isAuthenticated) {
      // 未登录，跳转到登录页
      next({
        name: 'login',
        query: { redirect: to.fullPath }
      })
    } else {
      // 这里可以添加管理员权限检查逻辑
      // 目前简单允许所有已登录用户访问
      next()
    }
  } else {
    next()
  }
}
